<?php

namespace backend\models;

use common\service\PubService;
use yii;

/**
 * This is the model class for table "baseareas".
 *
 * @property int $ID
 * @property int $ParentId
 * @property string $Name
 * @property string $MergerName
 * @property string $ShortName
 * @property string $MergerShortName
 * @property int $LevelType
 * @property string $CityCode
 * @property string $ZipCode
 * @property string $Pinyin
 * @property string $Jianpin
 * @property string $FirstChar
 * @property string $lng
 * @property string $Lat
 * @property string $Remark1
 * @property string $Remark2
 */
class Baseareas extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'baseareas';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['ID', 'ParentId'], 'required'],
            [['ID', 'ParentId', 'LevelType'], 'integer'],
            [['Name', 'ShortName', 'MergerShortName', 'CityCode', 'ZipCode', 'Pinyin', 'Jianpin', 'FirstChar', 'lng', 'Lat', 'Remark1', 'Remark2'], 'string', 'max' => 225],
            [['MergerName'], 'string', 'max' => 200],
            [['ID', 'ParentId'], 'unique', 'targetAttribute' => ['ID', 'ParentId']],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'ID' => 'ID',
            'ParentId' => 'Parent ID',
            'Name' => 'Name',
            'MergerName' => 'Merger Name',
            'ShortName' => 'Short Name',
            'MergerShortName' => 'Merger Short Name',
            'LevelType' => 'Level Type',
            'CityCode' => 'City Code',
            'ZipCode' => 'Zip Code',
            'Pinyin' => 'Pinyin',
            'Jianpin' => 'Jianpin',
            'FirstChar' => 'First Char',
            'lng' => 'Lng',
            'Lat' => 'Lat',
            'Remark1' => 'Remark1',
            'Remark2' => 'Remark2',
        ];
    }


    /**
     * 管理系统-设置区域代理
     */
    public function setareaAgent($data)
    {
        if (empty($data)) return ['statusCode'=>300, 'message'=>'参数缺失，请稍后再试'];
        if (empty($data['MasterId'])) return ['statusCode'=>300, 'message'=>'玩家ID丢失'];
        if (empty($data['Province'])) return ['statusCode'=>300, 'message'=>'请选择省份'];
        if (empty($data['City'])) return ['statusCode'=>300, 'message'=>'请选择城市'];
        if (empty($data['District'])) return ['statusCode'=>300, 'message'=>'请选择区县'];
        if (empty($data['AreaRevenue'])) return ['statusCode'=>300, 'message'=>'请输入税收比例'];
        if (empty($data['AreaRatio'])) return ['statusCode'=>300, 'message'=>'请输入区域比例'];
        //判断市级区域代理是否存在
        $areaCount = Basemaster::find()->where(['City'=>$data['City']])->count();
        $province = Baseareas::findOne(['ID'=>$data['Province']])->Name;
        $city = Baseareas::findOne(['ID'=>$data['City']])->Name;
        if ($areaCount) return ['statusCode'=>300, 'message'=>'【'.$province.$city.'】市级区域代理已存在'];
        $agent = Baseagency::findOne(['PlayerId'=>$data['MasterId']]);
        if ($agent){//层级代理数据存在
            $master = Basemaster::findOne(['MasterId'=>$agent->AdminId]);
            if (empty($master)) return ['statusCode'=>300, 'message'=>'层级代理身份丢失'];
            $master->AreaType = 2;
            $master->Province = $data['Province'];
            $master->City = $data['City'];
            $master->District = $data['District'];
            if ($master->save()){
                $agent->AreaRevenue = $data['AreaRevenue'];
                $agent->AreaRatio = $data['AreaRatio'];
                $agent->save();

                $log = new Baselogger();
                $log->LogLogic = '设置区域代理';
                $log->LogDescribe = '操作成功，成功设置区域代理！';
                $log->LogURL = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
                $log->LogDate = date('Y-m-d H:i:s', time());
                $log->LogIP = PubService::real_ip();
                $log->MasterId = $data['AdminId'];
                if ($log->save()){
                    return ['statusCode'=>200, 'message'=>'设置区域代理成功'];
                }
                return ['statusCode'=>300, 'message'=>$log->getFirstError()];
            }
            return ['statusCode'=>300, 'message'=>$master->getFirstError()];
        }else{//新增区域代理
            $agent = new Baseagency();
            $agent->ParentId = 0;
            $agent->PlayerId = $data['MasterId'];
            $agent->Level = 2;
            $agent->CollectDate = date('Y-m-d H:i:s', time());
            $agent->AreaRevenue = $data['AreaRevenue'];
            $agent->AreaRatio = $data['AreaRatio'];
            if ($agent->save()){
                //添加代理人员登录信息
                $master = new Basemaster();
                $userName = 'DL'.$data['MasterId'];
                $master->UserName = $userName;
                $master->LoginPass = md5($userName);
                $master->UserPass = md5($userName);
                $master->LoginDate = date('Y-m-d H:i:s', time());
                $master->LoginIP = PubService::real_ip();
                $master->UserType = 1;
                $master->AreaType = 1;
                $master->Province = $data['Province'];
                $master->City = $data['City'];
                $master->District = $data['District'];
                if ($master->save()){
                    $rolemaster = new Baserolemaster();
                    $rolemaster->MasterId = $master->MasterId;
                    $rolemaster->RoleId = 3;
                    if ($rolemaster->save()){
                        $agent->updateAll(['AdminId'=>$master->MasterId, 'FullDir'=>$agent->AgentId],'AgentId = :AgentId', [':AgentId'=>$agent->AgentId]);
                        $log = new Baselogger();
                        $log->LogLogic = '设置区域代理';
                        $log->LogDescribe = '操作成功，成功设置区域代理！';
                        $log->LogURL = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
                        $log->LogDate = date('Y-m-d H:i:s', time());
                        $log->LogIP = PubService::real_ip();
                        $log->MasterId = $data['AdminId'];
                        if ($log->save()){
                            return ['statusCode'=>200, 'message'=>'设置区域代理成功'];
                        }else{
                            return ['statusCode'=>300, 'message'=>'设置区域代理失败'];
                        }
                    }else{
                        return ['statusCode'=>300, 'message'=>'设置区域代理失败'];
                    }
                }else{
                    return ['statusCode'=>300, 'message'=>'设置区域代理失败'];
                }
            }
            return ['statusCode'=>300, 'message'=>'设置区域代理失败'];
        }
    }


    public function getAreaAgentList($post, $page, $pageSize)
    {
        if (empty($post['areaId'])){
            $where = 'a.AreaType > 0';
        }else{
            $where = 'a.AreaType > 0 and a.Province = '.$post['areaId'];
        }
        $order = "b.CollectDate desc";
        $offset = max(0, ($page-1))*$pageSize;
        if (isset($post['k']) && !empty($post['k'])){
            $k = $post['k'];
            $where .= " and (t.PlayerID = '{$k}' or t.PlayerName = '{$k}') ";
        }
        if (isset($post['s']) && !empty($post['s'])){
            $s = $post['s'].' 00:00:00';
            $where .= " and b.CollectDate >= '{$s}' ";
        }
        if (isset($post['f']) && !empty($post['f'])){
            $f = $post['f'].' 23:59:59';
            $where .= " and b.CollectDate <= '{$f}' ";
        }
        if (isset($post['columnSort']) && !empty($post['columnSort'])){
            $columnSort = json_decode($post['columnSort'])[0];
            $order = $columnSort->sortField.' '.$columnSort->dir;
        }
        $sql = "select *
                from basemaster a 
                inner join baseagency b on a.MasterId = b.AdminId 
                inner join Player_tbl t on b.PlayerId = t.PlayerID 
                where $where ";
        $orderby = "order by $order limit $pageSize offset $offset";
        $data = yii::$app->db->createCommand($sql.$orderby)->queryAll();
        foreach ($data as $key => $value){
            $province = Baseareas::findOne(['ID'=>$value['Province']]);//省份
            $city = Baseareas::findOne(['ID'=>$value['City']]);
            $data[$key]['Level'] = '市级';//empty($value['Level']) ? '总代' : ($value['Level'] == 1 ? '省级' : ($value['Level'] == 2 ? '市级' : '区级'));
            $data[$key]['DlName'] = 'DL'.$value['PlayerId'];
            $data[$key]['AreaAddr'] = $province->Name.$city->Name;
            $data[$key]['RegisterDate'] = date('Y-m-d H:i:s', $value['RegisterDate']);
        }
        $count = yii::$app->db->createCommand($sql)->queryAll();
        return ['data' => $data, 'limit'=> intval($pageSize) , 'page'=> intval($page), 'statusCode'=>200, 'total'=> count($count)];
    }


    /**
     * 区域代理提点分成
     */
    public function getAreaAgentVary()
    {
        $transation = Yii::$app->db->beginTransaction();
        try{
            $master = Basemaster::find()->where(['>', 'AreaType', 0])->andWhere(['UserType'=>1])->asArray()->all();
            $allPlayers = $players = [];
            foreach ($master as $key=>$val){
                $playerIds = self::getAreaPlayerList($val['City']);
                if ($playerIds){
                    $allPlayers[] = $playerIds;
                }
            }
            foreach ($allPlayers as $k=>$allPlayer) {
                foreach ($allPlayer as $i=>$item){
                    $players[] = $item;
                }
            }
            $result = ['status'=>0, 'message'=>'无数据'];
            foreach ($players as $playerid) {
                $hasAgent = PlayerTbl::findOne(['PlayerID'=>$playerid])->AgentID;
                if (empty($hasAgent)){//agentId为0，该玩家无层级代理，归属区域代理
                    $result = self::InsertNoAreaAgent($playerid);
                }else{//agentId不为0，该玩家存在层级代理，结算层级提点后，归属区域代理
                    $result = self::InsertHasAreaAgent($playerid);
                }
            }
            $sql ="SELECT sum(Balance) as Balance,AgentId FROM basebonus WHERE DATE_FORMAT(DrawDate, '%Y%m' ) = DATE_FORMAT( CURDATE( ) , '%Y%m' ) and Type = 1 group by AgentId";
            $data = yii::$app->db->createCommand($sql)->queryAll();
            foreach ($data as $val) {
                $agentcy = Baseagency::findOne(['PlayerId'=>$val['AgentId']]);
                $agentcy->Amount = $agentcy->Amount + $val['Balance'];
                $agentcy->UpdateDate = date('Y-m-d H:i:s', time());
                $agentcy->save();
            }
            $transation->commit();
            return ['status'=>1, 'message'=>'true'];
        }catch (\Exception $e){
            $transation->rollBack();
            return ['status'=>0, 'message'=>'false'];
        }

        return $result;
    }


    /**
     * @param $playerId
     * @throws yii\db\Exception
     * 层级代理和区域代理共有情况
     */
    private function InsertHasAreaAgent($playerId)
    {
        $nowTime = date('Y-m-d H:i:s', time());
        $sql = "SELECT sum(a.Balance) as Balance, a.OrderId, a.AgentId, a.UserId, a.Remarks, b.Amount  
                FROM basebonus a left join baseorders b on a.OrderId= b.OrderId 
                WHERE a.UserId = $playerId
                AND a.BalanceState = 1 and a.Type = 0 
                AND PERIOD_DIFF(date_format(now(),'%Y%m'),date_format(a.DrawDate,'%Y%m'))=1 group by a.OrderId";
        $data = yii::$app->db->createCommand($sql)->queryAll();
        $result = [];
        foreach ($data as $k => $datum) {
            $masagent = self::getVaryPlayerId($datum['UserId']);
            $revenue = $masagent->AreaRevenue;//区域税收比例
            $ratio = $masagent->AreaRatio;//区域比例
            $amount = $datum['Amount'];//充值金额
            $balance = $datum['Balance'];//层级提点金额
            $bamount = $amount - $balance;
            $bonus = $bamount * $revenue * $ratio;// （充值金额-层级提点） * 税收比例 * 区域比例
            $result[] = self::_arrayBatchData($datum['OrderId'], $masagent->PlayerId, $datum['UserId'], $bonus, $revenue, $ratio, $nowTime, $datum['Remarks']);
        }
        yii::$app->db->createCommand()->batchInsert('basebonus', ['OrderId', 'AgentId', 'Level', 'UserId', 'Balance', 'DrawScale', 'vary', 'BalanceState', 'DrawDate', 'BalanceDate', 'Remarks', 'Type'], $result)->execute();
        return ['status'=>1, 'message'=>'success'];
    }


    /**
     * @param $playerId
     * @throws yii\db\Exception
     * 无层级代理情况
     */
    private function InsertNoAreaAgent($playerId)
    {
        $nowTime = date('Y-m-d H:i:s', time());
        $sql = "SELECT *  
                FROM baseorders 
                WHERE UserId = $playerId
                AND PayStatus = 1 
                AND PERIOD_DIFF(date_format(now(),'%Y%m'),date_format(CollectDate,'%Y%m'))=1";
        $data = yii::$app->db->createCommand($sql)->queryAll();
        $result = [];
        foreach ($data as $k => $datum) {
            $masagent = self::getVaryPlayerId($datum['UserId']);
            $revenue = $masagent->AreaRevenue;//区域税收比例
            $ratio = $masagent->AreaRatio;//区域比例
            $bonus = $datum['Amount'] * $revenue * $ratio;// 充值金额 * 税收比例 * 区域比例
            $result[] = self::_arrayBatchData($datum['OrderId'], $masagent->PlayerId, $datum['UserId'], $bonus, $revenue, $ratio, $nowTime, '玩家充值');
        }
        yii::$app->db->createCommand()->batchInsert('basebonus', ['OrderId', 'AgentId', 'Level', 'UserId', 'Balance', 'DrawScale', 'vary', 'BalanceState', 'DrawDate', 'BalanceDate', 'Remarks', 'Type'], $result)->execute();
        return ['status'=>1, 'message'=>'success'];

    }

    private static function _arrayBatchData($OrderId, $AgentId, $UserId, $bonus, $revenue, $ratio, $nowTime, $remarks)
    {
        $batchData = [
            'OrderId' => $OrderId,
            'AgentId' => $AgentId,
            'Level' => 2,
            'UserId' => $UserId,
            'Balance' => $bonus,
            'DrawScale' => $revenue,
            'vary' => $ratio,
            'BalanceState' => 1,
            'DrawDate' => $nowTime,
            'BalanceDate' => $nowTime,
            'Remarks' => $remarks,
            'Type' => 1,
        ];
        return $batchData;
    }


    /**
     * @param $city
     * @return array
     * 获取区域代理下所有玩家的ID（包含区域代理自身）
     */
    public function getAreaPlayerList($city)
    {
        $cityId = $playerIds = [];
        $area = Baseareas::find()->where(['ID'=>$city])->orWhere(['ParentId'=>$city])->asArray()->all();
        foreach ($area as $key => $val){
            $cityId[] = $val['ID'];
        }
        $playertbl = PlayerTbl::find()->where(['in', 'AreaCode', $cityId])->asArray()->all();
        foreach ($playertbl as $key => $val){
            $playerIds[] = $val['PlayerID'];
        }
        return $playerIds;
    }


    /**
     * @param $city
     * @return array
     * 获取区域代理下所有玩家的ID（不包含区域代理自身）
     */
    private function getAreaNoPlayerList($city, $playerId)
    {
        $cityId = $playerIds = [];
        $area = Baseareas::find()->where(['ID'=>$city])->orWhere(['ParentId'=>$city])->asArray()->all();
        foreach ($area as $key => $val){
            $cityId[] = $val['ID'];
        }
        $playertbl = PlayerTbl::find()->where(['in', 'AreaCode', $cityId])->andWhere(['<>', 'PlayerID', $playerId])->asArray()->all();
        foreach ($playertbl as $key => $val){
            $playerIds[] = $val['PlayerID'];
        }
        return $playerIds;
    }

    /**
     * @param $playerid
     * @return null|static
     * 通过玩家Id查找税收比例
     */
    private static function getVaryPlayerId($playerid)
    {
        $ptb = PlayerTbl::findOne(['PlayerID'=>$playerid]);
        $area = Baseareas::findOne(['ID'=>$ptb->AreaCode]);
        if ($area->LevelType == 2){//市级ip地址
            $master = Basemaster::findOne(['City'=>$ptb->AreaCode]);
        }else{//区级ip
            $master = Basemaster::findOne(['City'=>$area->ParentId]);
        }
        $agent = Baseagency::findOne(['AdminId'=>$master->MasterId]);
        return $agent;
    }


    /**
     * 我的玩家List
     */
    public function getMyPlayerList($agent_city, $playerId, $post, $page, $pageSize)
    {
        $playerIds = self::getAreaNoPlayerList($agent_city, $playerId);
        $agentIds = implode(',', $playerIds);
        if (empty($agentIds)){
            $agentIds = 0;
        }
        $order = "t.RegisterDate desc";
        $where = " t.PlayerID in ({$agentIds}) ";
        $offset = max(0, ($page-1))*$pageSize;
        if (isset($post['k']) && !empty($post['k'])){
            $k = $post['k'];
            $where .= " and (t.PlayerID = '{$k}' or t.PlayerName = '{$k}') ";
        }
        if (isset($post['s']) && !empty($post['s'])){
            $s = $post['s'].' 00:00:00';
            $where .= " and t.RegisterDate >= '{$s}' ";
        }
        if (isset($post['f']) && !empty($post['f'])){
            $f = $post['f'].' 23:59:59';
            $where .= " and t.RegisterDate <= '{$f}' ";
        }
        if (isset($post['columnSort']) && !empty($post['columnSort'])){
            $columnSort = json_decode($post['columnSort'])[0];
            $order = $columnSort->sortField.' '.$columnSort->dir;
        }
        $sql = "select *,t.PlayerID in (select PlayerId from baseagency) as isAgent
                from Player_tbl as t 
                where $where ";
        $orderby = "order by $order limit $pageSize offset $offset";
        $data = yii::$app->db->createCommand($sql.$orderby)->queryAll();
        foreach ($data as $key=>$val){
            $data[$key]['RegisterDate'] = date('Y-m-d H:i:s', $val['RegisterDate']);
        }
        $count = yii::$app->db->createCommand($sql)->queryAll();
        return ['data' => $data, 'limit'=> intval($pageSize) , 'page'=> intval($page), 'statusCode'=>200, 'total'=> count($count)];
    }


}
